using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using CommonTestingUtils;
using LightPersist;
using LightPersist.Metainfo;
using LightPersist.Storage;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestDomainModel;


namespace LightPersistTests
{
	public abstract class TestsBase : FixtureMsTest
	{
		protected LightPersistContext Context;
		protected DomainMetainfo Domain;
		protected FakeRoot Root;
		protected Guid RootGuid;
		protected IStorage Storage;

		protected virtual IStorage CreateStorage()
		{
			return new InmemoryStorage();
		}

		protected string _log;
		protected void TraceToLog()
		{
			Trace.Listeners.Clear();
			Trace.AutoFlush = true;
			Trace.Listeners.Add(new TextWriterTraceListener(_log = Path.GetTempFileName()));
		}

		protected void LogInitializeComplete()
		{
			var st = new StackTrace(true).GetFrame(1);
			Trace.WriteLine(new string('=', 30) + " Test Initialized " + new string('=', 30)+ " {0}:{1}".Arg(st.GetMethod().Name, st.GetFileLineNumber()));
		}

		[TestInitialize]
		public void PrepareContext()
		{
			Storage = CreateStorage();
			Storage.Connect("_temp_storage_" + Guid.NewGuid());

			Context = new LightPersistContext(Storage, Domain = TestDomainModelMetainfo.Metainfo);

			SetRoot();

			LogInitializeComplete();
		}

		protected virtual void RecreateContext()
		{
			Context = new LightPersistContext(Storage, TestDomainModelMetainfo.Metainfo);
			ResetRoot();
		}

		protected virtual void SetRoot()
		{
			Root = Context.RootClass<FakeRoot>();
			RootGuid = Root.ID;
			using (var tr = Context.BeginTransaction())
			{
				Root.Name = "THE_ROOT";
				tr.CommitTransaction();
			}
		}

		protected virtual void ResetRoot()
		{
			using (var tr = Context.BeginTransaction())
			{
				Root = Context.GetObjectByID<FakeRoot>(RootGuid);
				tr.CommitTransaction();
			}
		}
	}
}